<?php
declare(strict_types=1);

namespace app\model;


use think\facade\Db;
use think\Model;

/**
 * Class SalesmanFinanceDaily
 *
 * @property int $id 自增id
 * @property string $dateymd 日期
 * @property int $order_total 订单总数
 * @property float|int $amount 订单金额。单位：分
 * @property int $serv_type 业务类型名，取值来自代码 constant->PRODUCT_SERV_TYPE
 * @property int $salesman_id 业务员ID
 * @property-read \app\model\Salesman $salesman
 * @property-read string $serv_type_format
 */
class SalesmanFinanceDaily extends Model
{
    /**
     * 关联业务员
     * @return \think\model\relation\HasOne
     */
    public function salesman()
    {
        return $this->hasOne(Salesman::class, 'id', 'salesman_id');
    }

    /**
     * 金额 分转成元
     * @param $value
     * @return float|int
     */
    public function getAmountAttr($value)
    {
        return $value ? number_format(fen2yuan($value), 2) : 0;
    }

    /**
     * serv_type供应商类型映射
     * @param $value
     * @param $model
     * @return string
     */
    public function getServTypeFormatAttr($value, $model)
    {
        return @PRODUCT_SERV_TYPE[$model['serv_type']]['name'] ?? '';
    }

    /**
     * 列表
     * @param $params
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function dataList($params)
    {
        $servType = $params['serv_type'] ?? PRODUCT_MOBILE_SERV;
        $salesmanId = $params['salesman_id'] ?? '';
        $dateStart = $params['date_start'] ?? '';
        $dateEnd = $params['date_end'] ?? '';

        $query = self::where(['serv_type' => $servType])
            ->when($salesmanId, function ($query) use ($salesmanId) {
                $query->where(['salesman_id' => $salesmanId]);
            });
        if ($dateStart && $dateEnd) {
            $dateEnd = $dateEnd . ' 23:59:59';
            $query->whereBetweenTime('dateymd', $dateStart, $dateEnd);
        }

        $query->order('dateymd desc');


        $cloneQuery = clone $query;  // 克隆一份查询统计 总订单数 总金额

        $list = $query->with(['salesman' => function ($query) {
            $query->withField(['id', 'true_name']);
        }])
            ->paginate()
            ->toArray();

        // 汇总所有的订单数据
        $amountNum = 0;
        $orderTotalNum = 0;
        if (!empty($list['data'])) {
            $orderCount = $cloneQuery->field(['sum(order_total) as order_total_sum, sum(amount) as amount_sum'])->select()->toArray();
            if ($orderCount && isset($orderCount[0])) {
                $amountNum = is_null($orderCount[0]['amount_sum']) ? 0 : round(fen2yuan($orderCount[0]['amount_sum']), 2);
                $orderTotalNum = is_null($orderCount[0]['order_total_sum']) ? 0 : $orderCount[0]['order_total_sum'];
            }
        }
        $list['amount_sum'] = $amountNum; // 业绩总额
        $list['order_total_sum'] = $orderTotalNum;  // 订单总数
        return $list;
    }

    /**
     * 获取当前业务员 所做业绩产品类型
     * @param $salesmanId
     * @return array
     */
    public function servTypeBySalesmanId($salesmanId)
    {
        $model = self::where(['salesman_id' => $salesmanId])
            ->field('serv_type')
            ->append(['serv_type_format'])
            ->group('serv_type')
            ->select()
            ->toArray();
        if (empty($model)) {
            // 空数据 默认话费
            $model = [
                [
                    'serv_type' => PRODUCT_MOBILE_SERV,
                    'serv_type_format' => '话费'
                ]
            ];
        }
        return $model;
    }
}